package com.itproject.manager.es.controller;

import com.alibaba.fastjson.JSON;
import com.itproject.manager.es.pojo.Goods;
import com.itproject.manager.es.pojo.User;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
public class GoodsController {

    @Autowired
    @Qualifier("highLevelClient")
    private RestHighLevelClient client;

    @RequestMapping(value = "/createIndex.do", method = RequestMethod.GET)
    public String createIndex() throws IOException {
        // 1、创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("goods_index");
        // 2、客户端执行创建请求, 请求完了获得响应, 判断是否存在
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        return  createIndexResponse.index();
    }

    @RequestMapping(value = "/delIndex.do", method = RequestMethod.GET)
    public String deleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("goods_index");
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        // 判断是否删除成功
        return String.valueOf(response.isAcknowledged());
    }

    @RequestMapping(value = "/addDoc.do", method = RequestMethod.GET)
    public String addDocument() throws IOException {
        // 创建对象
        Goods goods = new Goods();
        goods.setId("1");
        goods.setGoods_name("高山名茶");
        // 创建请求
        IndexRequest request = new IndexRequest("goods_index");
        // PUT /索引/_doc/1 不默认id为1的话会产生一个随机的id
        request.id("1");
        // 设置请求超时时间 request.timeout("1s");
        request.timeout(TimeValue.timeValueSeconds(1));
        // 将我们的数据放入请求 json 发出请求
        request.source(JSON.toJSONString(goods), XContentType.JSON);
        // 客户端发出请求 获取响应结果
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        return indexResponse.toString();
    }

    @RequestMapping(value = "/getDoc.do", method = RequestMethod.GET)
    public String getDocument() throws IOException {
        GetRequest request = new GetRequest("goods_index", "1");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        // 获取指定字段 userName
        //response.getField("goodsName");
        return response.getSourceAsString();
    }

    @RequestMapping(value = "/updateDoc.do", method = RequestMethod.GET)
    public String updateDocument() throws IOException {
        UpdateRequest request = new UpdateRequest("goods_index", "1");
        // 请求最大时长1s
        request.timeout(TimeValue.timeValueSeconds(1));
        Goods goods = new Goods();
        goods.setGoods_name("高山名茶2");
        // 更新文档 POST /索引/_doc/文档/_update  doc [field = ""]
        request.doc(JSON.toJSONString(goods), XContentType.JSON);
        // 执行请求
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        return "update success";
    }

    @RequestMapping(value = "/bulkGet.do", method = RequestMethod.GET)
    public void bulkGet() throws IOException {
        SearchRequest searchRequest = new SearchRequest("goods_index");
        // 构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 分页
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(10);
        // 高亮构建
        // searchSourceBuilder.highlighter();
        // 构建条件查询
        // 模糊查询
        // MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("userName", "AA");
        // 查询所有
        // MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        // 精确查询
        MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery("goods_name", "高山");
        // 这个失效了, 可以使用上面的
        // TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("userName", "AA");
        searchSourceBuilder.query(matchPhraseQueryBuilder);

        // 时间不能超过10s
        // searchSourceBuilder.timeout(TimeValue.timeValueSeconds(10));
        searchSourceBuilder.timeout(new TimeValue(10, TimeUnit.SECONDS));
        // 放入请求
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        // 所有的数据都在hits里面
        System.out.println("response.getHits() = " + JSON.toJSONString(response.getHits()));
        System.out.println(" ============== ");
        for (SearchHit documentFields : response.getHits().getHits()) {
            // 打印数据
            System.out.println(documentFields.getSourceAsMap());
        }
    }
}
